/*
 * @Author: your name
 * @Date: 2020-08-26 16:34:42
 * @LastEditTime: 2020-08-28 10:47:50
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /express/router.ts
 */
import {Router, Request, Response, NextFunction} from 'express';

interface BodyRequest extends Request {
  body: { [key: string]: string | undefined };
}

const checkLogin = (req:Request, res:Response, next:NextFunction) => {
  const isLogin = req.session ? req.session.login : false;
  if(isLogin) {
    next();
  }else {
    res.json('请登录')
  }
}

const router = Router();

router.get('/', (req: BodyRequest, res: Response) => {
  const isLogin = req.session ? req.session.login : false;
  if(isLogin) {
    res.send(`
      <html>
        <body>
          <a href='/getData'>爬取内容</a>
          <a href='/showData'>展示内容</a>
          <a href='/logout'>退出</a>
        </body>
      </html>
    `)
  } else {
    res.send(`
      <html>
        <body>
          <form method="post" action="/login">
            <input type="password" name="password" />
            <button>登陆</button>
          </form>
        </body>
      </html>
    `);
  }
})

router.get('/logout', (req: BodyRequest, res: Response) => {
  if (req.session) {
    req.session.login = undefined;
  }
  res.json(true);
});

router.post('/login', (req: BodyRequest, res: Response) => {
  const { password } = req.body;
  const isLogin = req.session ? req.session.login : false;
  console.log(res)
  if (isLogin) {
    res.json('已经登陆过');
  } else {
    if (password === '123' && req.session) {
      req.session.login = true;
      res.json((true));
    } else {
      res.json( '登陆失败' );
    }
  }
});

router.get('/getData', (req: Request, res: Response) => {
  res.send('getData')
});

export default router;
